<template>
  <div>
    <ul>
      <li v-for="item in msgList" :key="item.id">
        <p>
          <span>{{ item.dateTime }}</span>
        </p>
        <p>
          <span>{{ item.user }}: {{ item.msg }}</span>
        </p>
      </li>
    </ul>
    <input
      type="text"
      placeholder="请输入消息"
      v-model="msg"
      @keyup.enter="handleSentBtnClick"
    />
    <button @click="handleSentBtnClick">发送</button>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs } from 'vue';
import { useRouter } from 'vue-router';
import useWebsocket from '../hooks';
// 时间格式化函数
function getTime() {
  const time = new Date();
  let h = time.getHours();
  h = h < 10 ? `0${h}` : h;
  let m = time.getMinutes();
  m = m < 10 ? `0${m}` : m;
  let s = time.getSeconds();
  s = s < 10 ? `0${s}` : s;
  return `${h}:${m}:${s}`;
}

export default {
  name: 'Home',
  setup() {
    const router = useRouter();
    const state = reactive({
      msg: '',
      msgList: [],
    });
    let username = '';
    // 获取用户名
    onMounted(() => {
      username = localStorage.getItem('username');
      if (!username) {
        router.push('/login');
      }
    });
    // 接收服务器返回消息，并将消息发送到列表
    function handleMessage(e) {
      // 接收后端返回的消息
      const tempMsgData = JSON.parse(e.data);
      // 向消息列表添加消息
      state.msgList.push(tempMsgData);
    }
    const ws = useWebsocket(handleMessage);
    // 发送消息到服务器事件方法
    const handleSentBtnClick = () => {
      const tempMsg = state.msg.trim();
      // 判断消息不为空
      if (!tempMsg.length) {
        return;
      }
      // 向服务器发送消息
      ws.send(
        JSON.stringify({
          id: Math.ceil(Math.random() * 100),
          user: username,
          dateTime: getTime(),
          msg: state.msg,
        }),
      );
      state.msg = '';
    };
    return {
      ...toRefs(state),
      handleSentBtnClick,
    };
  },
};
</script>

<style>
</style>
